package com.zm.zmgz.controller.salarySettlement;

import com.zm.zmgz.annotationzm.ButtonAuthorityAnnotation;
import com.zm.zmgz.annotationzm.LoginRequired;
import com.zm.zmgz.pojo.*;
import com.zm.zmgz.service.EmployeeService;
import com.zm.zmgz.service.SalarySettlementDetailsService;
import com.zm.zmgz.service.SalarySettlementService;
import com.zm.zmgz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/03/25/10:26
 * @Description: 对应前端工资结算index模块
 */

@RestController
@RequestMapping("/salarySettlement/salarySettlementIndex")
public class SalarySettlementIndexController {

    @Autowired
    SalarySettlementService salarySettlementService;

    @Autowired
    SalarySettlementDetailsService salarySettlementDetailsService;

    @Autowired
    EmployeeService employeeService;

    @Autowired
    UserService userService;



    /***
     * @Description: 导入excel
     * @Param:-
     * 步骤:检查
     *        是否为空,或长度为0
     *        检查姓名,身份证,联系电话,状态是否为空(0,1,2)
     *     事务内
     *        根据主键删除
     *        根据主键新增
     *     返回Boolean，及提示信息
     * @return:
     * @Author: cjw
     * @Date: 2020-04-20 14:17:42
     */
    @LoginRequired // 需要登录
    @PutMapping("/importExcel")
    @Transactional
    public Response importExcel(@RequestHeader("X-Token") String token,@RequestBody List<SalarySettlementDetailsBean> beans){
        if(Objects.isNull(beans) || beans.size() == 0) {
            return new Response(20000,"导入数据为空或数据错误,请检查导入文件!",false);
        }
        System.err.println(beans);
        for (SalarySettlementDetailsBean salarySettlementDetailsBean : beans) { // 检查姓名,身份证,联系电话,状态是否为空(0,1,2)
            if(Objects.isNull(salarySettlementDetailsBean.getName())) {
                return new Response(20000,"姓名不能为空!",false);
            }
            if(Objects.isNull(salarySettlementDetailsBean.getIdentificationnumber())) {
                return new Response(20000,"身份证不能为空!",false);
            }
        }
        for (SalarySettlementDetailsBean bean : beans) {
            salarySettlementDetailsService.deleteByBatchAndIdentificationnumber(bean);
        }
        for (SalarySettlementDetailsBean bean : beans) {
            salarySettlementDetailsService.addSalarySettlementDetail(bean);
        }

        return new Response(20000,"导入成功!",true);
    }

    /***
    * @Description: 获取新增批次明细模板数据
    * @Param: 
    * @return: 
    * @Author: cjw
    * @Date: 2020-04-22 17:42:03
    */
    @LoginRequired
    @GetMapping("/getDetailTemplate")
//    @ButtonAuthorityAnnotation("/salarySettlement/salarySettlementIndex/handleBatchStatusChange")
    public Response getDetailTemplate(@RequestHeader("X-Token") String token, String identificationnumber) {
        SalarySettlementDetailsBean salarySettlementDetailsBean = salarySettlementDetailsService.getDetailTemplate(identificationnumber);
        return !Objects.isNull(salarySettlementDetailsBean) ? new Response(20000, "获取新增批次明细模板数据成功!", salarySettlementDetailsBean) : new Response(20000, "获取新增批次明细模板数据失败!", null);
    }

    /***
     * @Description: 把该批次状态取反
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-04-01 18:36:35
     */
    @LoginRequired
    @PutMapping("/handleBatchStatusChange")
    @ButtonAuthorityAnnotation("/salarySettlement/salarySettlementIndex/handleBatchStatusChange")
    public Response handleBatchStatusChange(@RequestHeader("X-Token") String token, Integer id) {
        if (Objects.isNull(id)) {
            SalarySettlementBean newestSalarySettlement = salarySettlementService.getNewestSalarySettlement();
            id = newestSalarySettlement.getId();
        }
        int i = salarySettlementService.handleBatchStatusChange(id);
        return id > 0 ? new Response(20000, "冻结或解封成功!", true) : new Response(20000, "冻结或解封失败!", false);
    }

    /***
     * @Description: 根据批次id, 删除该批次
     * @Param: handleBatchDelete
     * @return:
     * @Author: cjw
     * @Date: 2020-03-31 17:36:02
     */
    @LoginRequired
    @DeleteMapping("/handleBatchDelete")
    @ButtonAuthorityAnnotation("/salarySettlement/salarySettlementIndex/batchDelete")
    public Response handleBatchDelete(@RequestHeader("X-Token") String token, int id) {
        int i = salarySettlementService.handleBatchDelete(id);
        return id > 0 ? new Response(20000, "第" + id + "批次删除成功!", true) : new Response(20000, "第" + id + "批次删除成功!", false);
    }

    /***
     * @Description: 获取批次信息
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-31 13:01:32
     */
//    @LoginRequired
    @GetMapping("/getBatchOptions")
    public Response getBatchOptions() {
        List<BatchOptionsBean> batchOptionsBeans = salarySettlementService.getBatchOptions();
        return !Objects.isNull(batchOptionsBeans) && batchOptionsBeans.size() > 0 ? new Response(20000, "批次信息获取成功!", batchOptionsBeans) : new Response(20000, "批次信息获取失败!", null);
    }

    /***
     * @Description: 根据批次id获取姓名可选项
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-31 10:03:27
     */
    @LoginRequired
    @GetMapping("/getNameOptions")
    public Response getNameOptions(String batch) {
        System.out.println("获取姓名可选项批次id:" + batch);
        List<SalarySettlementDetailsBean> salarySettlementDetailsBeanList = salarySettlementDetailsService.getSalarySettlementDetailsByBatch(Integer.parseInt(batch), 0, 0);
        List<String> list = new ArrayList<>();
        if (!Objects.isNull(salarySettlementDetailsBeanList) && salarySettlementDetailsBeanList.size() > 0) {
            for (SalarySettlementDetailsBean salarySettlementDetailsBean : salarySettlementDetailsBeanList) {
                list.add(salarySettlementDetailsBean.getIdentificationnumber());
            }
        }
        List<Map<String, String>> mapList = employeeService.getNameOptions(list);
        return !Objects.isNull(mapList) ? new Response(20000, "第" + batch + "批次可用姓名选项:" + mapList, mapList) : new Response(20000, "第" + batch + "批次无可用姓名选项!", null);
    }

    /***
     * @Description: 添加一个salarySettlementDetailsBean(收支明细对象)
     * @Param: SalarySettlementDetailsBean
     * @return: Boolean
     * @Author: cjw
     * @Date: 2020-03-31 07:17:37
     */
    @LoginRequired
    @PostMapping("/addSalarySettlementDetail")
    @ButtonAuthorityAnnotation("/salarySettlement/salarySettlementIndex/add")
    public Response addSalarySettlementDetail(@RequestHeader("X-Token") String token, @RequestBody SalarySettlementDetailsBean salarySettlementDetailsBean) {
        System.out.println("新增一个明细批次:" + salarySettlementDetailsBean);
        if (Objects.isNull(salarySettlementDetailsBean)) {
            return new Response(20000, "批次明细新增失败!", false);
        }
        int i = salarySettlementDetailsService.addSalarySettlementDetail(salarySettlementDetailsBean);
        return i > 0 ? new Response(20000, salarySettlementDetailsBean.getName() + "批次明细新增成功!", true) : new Response(20000, salarySettlementDetailsBean.getName() + "批次明细新增成功!", false);
    }

    /***
     * @Description: 返回一个空的salarySettlementDetailsBean对象, 作为添加的空模板
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-30 17:34:22
     */
    @LoginRequired
    @GetMapping("/getNullRowData")
    public Response getNullRowData() {
        return 1 == 1 ? new Response(20000, "获取salarySettlementDetailsBean空对象成功!", new SalarySettlementDetailsBean()) : new Response(20000, "获取salarySettlementDetailsBean空对象失败!", null);
    }

    /***
     * @Description: 把传入的结算明细状态取反
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-30 16:27:18
     */
    @LoginRequired
    @PutMapping("/updateSingleStatus")
    @ButtonAuthorityAnnotation("/salarySettlement/salarySettlementIndex/issue")
    public Response updateSingleStatus(@RequestHeader("X-Token") String toke, @RequestBody SalarySettlementDetailsBean salarySettlementDetailsBean) {

        String name = userService.getUserNameByidentificationNumber(toke);
        int i = salarySettlementDetailsService.updateSingleStatus(salarySettlementDetailsBean, name);
        return i > 0 ? new Response(20000, "第" + salarySettlementDetailsBean.getBatch() + "批次工资" + salarySettlementDetailsBean.getName() + "的工资发放或暂缓成功!", true) : new Response(20000, "第" + salarySettlementDetailsBean.getBatch() + "批次工资" + salarySettlementDetailsBean.getName() + "的工资发放或暂缓成功!", false);
    }


    /***
     * @Description: 删除一个SalarySettlementDetailsBean
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-28 10:08:42
     */
    @LoginRequired
    @DeleteMapping("/handleDelete")
    @ButtonAuthorityAnnotation("/salarySettlement/salarySettlementIndex/delete")
    public Response handleDelete(@RequestHeader("X-Token") String token, @RequestBody SalarySettlementDetailsBean row) {
        int i = salarySettlementDetailsService.handleDelete(row);
        return i > 0 ? new Response(20000, "删除" + row.getName() + "本批次工资结算记录成功!", i) : new Response(20000, "删除" + row.getName() + "本批次工资结算记录成功!", i);
    }

    /***
     * @Description: 根据批次id, 全部发放或暂缓
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-27 19:49:54
     */
    @LoginRequired
    @PutMapping("/allIssueOrHoldOff")
    @ButtonAuthorityAnnotation("/salarySettlement/salarySettlementIndex/batchIssue")
    public Response allIssueOrHoldOff(@RequestHeader("X-Token") String token, @RequestBody AllIssueOrHoldOffBean allIssueOrHoldOffBean) {

        allIssueOrHoldOffBean.setName(userService.getUserNameByidentificationNumber(token));
        allIssueOrHoldOffBean.setDate(new Date());
        if (Objects.isNull(allIssueOrHoldOffBean.getId())) {
            SalarySettlementBean newestSalarySettlement = salarySettlementService.getNewestSalarySettlement();
            allIssueOrHoldOffBean.setId(newestSalarySettlement.getId());
        }
        Boolean aBoolean = salarySettlementDetailsService.allIssueOrHoldOff(allIssueOrHoldOffBean);
        return aBoolean ? new Response(20000, "第" + allIssueOrHoldOffBean.getId() + "批次工资全部发放或暂缓成功!", aBoolean) : new Response(20000, "第" + allIssueOrHoldOffBean.getId() + "批次工资全部发放或暂缓成功!", aBoolean);
    }

    /***
     * @Description: 该批次是否全部发放完毕
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-27 19:09:53
     */
    @LoginRequired
    @GetMapping("/getStatusAll")
    public Response getStatusAll(Integer id) {
        Boolean aBoolean = salarySettlementDetailsService.getStatusAll(id);
        return aBoolean ? new Response(20000, "第" + id + "批次全部发放完毕!", aBoolean) : new Response(20000, "第" + id + "批次没有全部发放完毕!", aBoolean);
    }

    /***
     * @Description: 更新SalarySettlementDetailsBean
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-27 01:31:29
     */
    @LoginRequired
    @PutMapping("/updateSalarySettlementDetail")
    @ButtonAuthorityAnnotation("/salarySettlement/salarySettlementIndex/edit")
    public Response updateSalarySettlementDetail(@RequestHeader("X-Token") String token, @RequestBody SalarySettlementDetailsBean salarySettlementDetail) {
        System.out.println("需要更新的结算明细:" + salarySettlementDetail);
        int i = salarySettlementDetailsService.updateSalarySettlementDetail(salarySettlementDetail);
        return i > 0 ? new Response(20000, salarySettlementDetail.getName() + "工资结算更新成功!", true) : new Response(20000, salarySettlementDetail.getName() + "工资结算更新失败!", false);
    }

    /***
     * @Description: 根据batchValue(批次), 获取SalarySettlementDetailsList
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-26 21:12:13
     */
    @LoginRequired
    @GetMapping("/getSalarySettlementDetailsList")
    public Response getSalarySettlementDetailsList(Integer id, int page, int limit) {
        List<SalarySettlementDetailsBean> salarySettlementDetailsBeanList = salarySettlementDetailsService.getSalarySettlementDetailsByBatch(id, page, limit);
        return Objects.isNull(salarySettlementDetailsBeanList) ? new Response(20000, "第" + id + "批次暂无明细数据！", null) : new Response(20000, "第" + id + "批次明细数据获取成功！", salarySettlementDetailsBeanList);
    }

    /***
     * @Description: 根据id获取批次(为空获取最新批次), 批次table tag
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020年3月25日 22点07分
     */
    @LoginRequired
    @GetMapping("/getTableTag")
    public Response getTableTag(String id) {
        String tableTag = salarySettlementService.getTableTagById(id);
        return Objects.isNull(tableTag) ? new Response(20000, "Table Tag数据获取失败!", null) : new Response(20000, "Table Tag数据获取成功!", tableTag);
    }


    /***
     * @Description: 根据id获取批次, 批次为空返回最新批次数据
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-03-25 17:33:04
     */
    @LoginRequired
    @GetMapping("/getSalarySettlement")
    public Response getSalarySettlement(String id) {
        if (Objects.isNull(id)) {
            SalarySettlementBean salarySettlementBean = salarySettlementService.getNewestSalarySettlement();
            return Objects.isNull(salarySettlementBean) ? new Response(20000, "暂无批次数据!", null) : new Response(20000, salarySettlementBean.getId() + "批次信息获取成功!", salarySettlementBean);
        } else {
            SalarySettlementBean salarySettlementBean = salarySettlementService.getSalarySettlementById(id);
            return Objects.isNull(salarySettlementBean) ? new Response(20000, "暂无" + id + "批次!", null) : new Response(20000, id + "批次信息获取成功!", salarySettlementBean);
        }

    }

    /***
     * @Description: 首先在工资结算表中新增一条记录，赋值创建时间，创建用户和状态（解封），并获取自增的主键值。
     *
     *
     * 从员工信息表搜索（离职排除），对批次id，姓名，身份证进行赋值。 salarySettlementIndexService.addBatch(); // 新建一个批次
     * @Author: cjw
     */
    @Transactional
    @GetMapping("/handleBatchAdd") // url
    @LoginRequired // 需要登录
    @ButtonAuthorityAnnotation("/salarySettlement/salarySettlementIndex/batchAdd")
    public Response handleBatchAdd(@RequestHeader("X-Token") String identificationNumber, String month) {
        int j = 0;
        List<SalarySettlementDetailsBean> salarySettlementDetailsBeanList = new ArrayList<>();
        SalarySettlementBean salarySettlementBean = salarySettlementService.addBatch(identificationNumber,new Date(Long.parseLong(month))); // 新增一个批次
        // 不存在最近批次或者不存在最近批次明细记录,就从员工表中提取原始数据.
        List<EmployeeBean> employeeBeanList = employeeService.getNoLeaveEmployees(); // 获取非离职员工集合
        int i = 1; // 批次内id
        if (employeeBeanList.size() > 0) {
            for (EmployeeBean employeeBean : employeeBeanList) { // 设置身份证,批次id,批次内id,状态(未发放)及其他默认值
                SalarySettlementDetailsBean salarySettlementDetailsBean = new SalarySettlementDetailsBean();
                salarySettlementDetailsBean.setIdentificationnumber(employeeBean.getIdentificationnumber());
                salarySettlementDetailsBean.setProjectname(employeeBean.getProjectname());

                salarySettlementDetailsBean.setCoefficient("21.75"); // 设置系数

                BigDecimal trialsalary = null;
                if(employeeBean.getStatus().equals("0")){
                    trialsalary = employeeBean.getTrialsalary();
                } else {
                    trialsalary = employeeBean.getSalary();
                }
                if(!Objects.isNull(trialsalary)) {
                    trialsalary = trialsalary.multiply(new BigDecimal(1000));
                    salarySettlementDetailsBean.setBasicwage(trialsalary.toString()); // 设置基本工资
                    salarySettlementDetailsBean.setDayrate(trialsalary.divide(new BigDecimal(21.75), 2)); // 设置日均工资,保留两位小数,有余数末尾加1
                }
                salarySettlementDetailsBean.setNeeddays(new BigDecimal(21)); // 设置应出勤天数
                salarySettlementDetailsBean.setTruedays(new BigDecimal(21)); // 设置实际出勤天数
                salarySettlementDetailsBean.setBatch(salarySettlementBean.getId());
                salarySettlementDetailsBean.setBatchid(i++);
                salarySettlementDetailsBean.setStatus("未发放");
                salarySettlementDetailsBeanList.add(salarySettlementDetailsBean);
            }
        } else {
            System.out.println("没有就职员工!");
        }
        j = salarySettlementDetailsService.addSalarySettlementDetails(salarySettlementDetailsBeanList);
        System.out.println("工资结算明细表(初始化)新增记录:" + j);
        return j == 0 ? new Response(20000, "批次添加失败!", false) : new Response(20000, "批次添加成功s!", true);
    }
}
